package com.huluobo.a2204monthdemo.home

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.a2204monthdemo.R
import com.huluobo.a2204monthdemo.adapter.HomeGoodsAdapter
import com.huluobo.a2204monthdemo.adapter.HomeHotAdapter
import com.huluobo.a2204monthdemo.adapter.NavAdapter
import com.huluobo.a2204monthdemo.databinding.FragmentHomeBinding
import com.huluobo.a2204monthdemo.detail.DetailActivity
import com.huluobo.a2204monthdemo.utils.ImageUtils
import com.huluobo.base.bean.HomeGoodsBean
import com.huluobo.base.bean.HomeNavBean
import com.huluobo.base.net.Const
import com.huluobo.base.view.BaseMVVMFragment
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.youth.banner.BannerConfig
import com.youth.banner.loader.ImageLoader

class HomeFragment : BaseMVVMFragment<FragmentHomeBinding, HomeViewModel>() {
    private lateinit var homeGoodsAdapter: HomeGoodsAdapter
    private val homeGoodsList = mutableListOf<HomeGoodsBean>()
    private val bannerList = mutableListOf<String>()
    private var currentPage = 1
    private lateinit var navAdapter: NavAdapter
    private val navList = mutableListOf<HomeNavBean>()
    private lateinit var hotAdapter: HomeHotAdapter
    override fun getLayoutId(): Int = R.layout.fragment_home

    override fun initData() {
        viewModel.getHomeGoodsList(0, currentPage, 10)
        viewModel.getHomeBanner()
        viewModel.getHomeNav()

        viewModel.getHomeNavSuccess.observe(this) {
            Log.i("TagA", "nav:${it.data[0].data?.size}")
            if (it.code == 200) {
                navList.clear()
                navList.addAll(it.data[0].data!!)
                navAdapter.notifyDataSetChanged()
            } else {
                ToastUtils.showLong(it.message)
            }
        }

        viewModel.getHomeNavFailed.observe(this) {
            Log.i("TagA", "获取首页导航失败:$it")
        }

        viewModel.getHomeBannerSuccess.observe(this) {
            if (it.code == 200) {
                bannerList.clear()
                it.data.forEach {
                    bannerList.add(it.imagePath)
                }
                dataBinding.homeBanner.setImages(bannerList)
                dataBinding.homeBanner.start()
            }
        }

        viewModel.getHomeBannerFailed.observe(this) {
            Log.i("TagA", "获取首页banner失败:$it")
        }
        viewModel.getHomeGoodsListSuccess.observe(this) {
            if (it.code == 200) {
                if (currentPage == 1) {
                    homeGoodsList.clear()
                }
                dataBinding.homeSrl.finishRefresh()
                dataBinding.homeSrl.finishLoadMore()
                homeGoodsList.addAll(it.data)
                homeGoodsAdapter.notifyDataSetChanged()
                hotAdapter.notifyDataSetChanged()
            } else {
                ToastUtils.showLong(it.message)
            }
        }

        viewModel.getHomeGoodsListFailed.observe(this) {
            Log.i("TagA", "获取首页商品列表失败:$it")
        }
    }

    override fun initView() {
        dataBinding.homeRv.layoutManager = GridLayoutManager(requireContext(), 2)
        homeGoodsAdapter = HomeGoodsAdapter(homeGoodsList)
        dataBinding.homeRv.adapter = homeGoodsAdapter

        homeGoodsAdapter.setOnItemClickListener { adapter, view, position ->
            postGoodsId(homeGoodsList[position].id)
        }

        dataBinding.homeBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
        dataBinding.homeBanner.setImageLoader(object : ImageLoader() {
            override fun displayImage(context: Context?, path: Any?, imageView: ImageView?) {
                if (context != null && imageView != null) {
                    ImageUtils.loadImage(context, path.toString(), imageView)
                }
            }
        })
        dataBinding.homeBanner.setDelayTime(2000)
        dataBinding.homeBanner.setIndicatorGravity(BannerConfig.CENTER)

        dataBinding.homeSrl.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                if (refreshLayout.isLoading) {
                    refreshLayout.finishLoadMore()
                }
                currentPage = 1
                viewModel.getHomeGoodsList(0, currentPage, 10)
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                if (refreshLayout.isRefreshing) {
                    refreshLayout.finishRefresh()
                }
                currentPage += 1
                viewModel.getHomeGoodsList(0, currentPage, 10)
            }
        })

        dataBinding.homeNavRv.layoutManager = GridLayoutManager(requireContext(), 5)
        navAdapter = NavAdapter(navList)
        dataBinding.homeNavRv.adapter = navAdapter

        dataBinding.homeHotGoodsRv.layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
        hotAdapter = HomeHotAdapter(homeGoodsList)
        dataBinding.homeHotGoodsRv.adapter = hotAdapter

        hotAdapter.setOnItemClickListener { adapter, view, position ->
            postGoodsId(homeGoodsList[position].id)
        }

    }

    override fun getViewModel(): Class<HomeViewModel> {
        return HomeViewModel::class.java
    }

    fun postGoodsId(goodsId: Int) {
        val intent = Intent(requireContext(), DetailActivity::class.java)
        intent.putExtra(Const.PARAM_GOODS_ID, goodsId)
        startActivity(intent)
    }
}